import {Component, EventEmitter, OnInit, Input, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {RmService} from '../rm.service';

@Component({
  selector: 'app-rm-add',
  templateUrl: 'rm-add.component.html',
  styleUrls: ['rm-add.component.css']
})
export class RmAddComponent implements OnInit {
  // ------------------------------------------------------------------------------------------
  @ViewChild('resetFormComponent') resetFormComponent;
  @Output() refreshData = new EventEmitter();
  isVisible = false;
  validateForm: FormGroup;
  tourisms: any[] = [];
  perUnitPrice: any;
  touism: any;
  grossPrice: any = 0;
  e: any = 0;
  showModal(): void {
    this.isVisible = true;
  }

  handleOk(): void {
    const isSuccess: boolean = this.submitForm();
    if (isSuccess) {
      this.resetForm();
      this.isVisible = false;
    }
  }

  handleCancel(): void {
    this.resetForm();
    this.isVisible = false;
  }

  getInvalid(name) {
    return this.resetFormComponent.getInvalidMessage(name);
  }

  submitForm() {
    const data: Element = new Element();
    if (!this.resetFormComponent.validForm()) {
      return false;
    } else {
      for (const i in this.validateForm.controls) {
        if (i) {
          this.validateForm.controls[i].markAsDirty();
          data[i] = this.validateForm.controls[i].value;
        }
      }
      this.create(data);
      return true;
    }
  }

  resetForm(): void {
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      if (key) {
        this.validateForm.controls[key].markAsPristine();
      }
    }
  }
  nzBlur (e) {
    this.e = e;
    this.grossPrice = e * this.perUnitPrice;
  }
  onSearch(e) {
    this.mainService.getByid(e).subscribe(response => {
      this.touism = response;
      if (this.touism != null) {
        this.perUnitPrice = this.touism.perUnitPrice;
        this.grossPrice = this.e * this.perUnitPrice;
      }
    });
  }
  create(data) {
    this.mainService.create(data).subscribe(respose => this.refreshData.emit());
  }

  // -------------------------------------------------------------------------------------------------------------------------

  constructor(private fb: FormBuilder,
              private router: Router,
              private activatedRoute: ActivatedRoute,
              private mainService: RmService) {
    this.validateForm = this.fb.group({
      applicant: [null, [Validators.required]],
      apmId: [null, [Validators.required]],
      numbers: [null, [Validators.required]],
      grossPrice: [null, [Validators.required]]
    });
  }
  ngOnInit() {
     this.mainService.getData().subscribe(response => {
      this.tourisms = response;
    });
  }
}

export class Element {
  id: any;
  applicant: any;
  apmId: any;
  numbers: any;
  grossPrice: any;
}